import Vue from "vue";
import Vuex from "vuex";
import connectMqtt from "@/common/mqtt.js";

Vue.use(Vuex);

let lifeData = {};

try {
  // 尝试获取本地是否存在lifeData变量，第一次启动APP和清空后时是不存在的
  lifeData = uni.getStorageSync("lifeData");
} catch (e) {
  uni.setStorageSync("lifeData", {});
}

// 需要永久存储，且下次APP启动需要取出的，在state中的变量名
let saveStateKeys = ["userInfo"];

// 保存变量到本地存储中
const saveLifeData = function (key, value) {
  // 判断变量名是否在需要存储的数组中
  if (saveStateKeys.indexOf(key) != -1) {
    // 获取本地存储的lifeData对象，将变量添加到对象中
    let tmp = uni.getStorageSync("lifeData");
    // 第一次打开APP，不存在lifeData变量，故放一个{}空对象
    tmp = tmp ? tmp : {};
    tmp[key] = value;
    // 执行这一步后，所有需要存储的变量，都挂载在本地的lifeData对象中
    uni.setStorageSync("lifeData", tmp);
  }
};

const store = new Vuex.Store({
  state: {
    mqtt: null,
    globalData: {
      statusBarHeight: 0, // 状态导航栏高度
      navigationBarHeight: 0, // 导航栏高度(标题栏高度)
      navHeight: 0, // 总体高度
      windowWidth: 0, // 可使用窗口宽度
      windowHeight: 0, // 可使用窗口高度
      bottomSafeHeight: 0, // 底部安全距离
      brand: "", // 机型
    },
    appData: {},
    userInfo: {},
    choseFriendInfo: {},
    messageValue: 0,
  },
  mutations: {
    $uStore(state, payload) {
      // 判断是否多层级调用，state中为对象存在的情况，诸如user.info.score = 1
      let nameArr = payload.name.split(".");
      // console.log("我被调用了", payload, nameArr);
      let saveKey = "";
      let len = nameArr.length;
      if (nameArr.length && nameArr.length >= 2) {
        let obj = state[nameArr[0]];
        for (let i = 1; i < len - 1; i++) {
          obj = obj[nameArr[i]];
        }
        obj[nameArr[len - 1]] = payload.value;
        saveKey = nameArr[0];
      } else {
        // 单层级变量，在state就是一个普通变量的情况
        state[payload.name] = payload.value;
        saveKey = payload.name;
      }
      // 保存变量到本地，见顶部函数定义
      saveLifeData(saveKey, state[saveKey]);
    },
    // 获取设备信息
    getSystemInfo(state) {
      const systemInfo = uni.getSystemInfoSync();
      state.globalData.statusBarHeight = systemInfo.statusBarHeight;
      state.globalData.bottomSafeHeight = systemInfo.safeAreaInsets.bottom;
      state.globalData.brand = systemInfo.deviceBrand;
      // #ifdef MP-WEIXIN
      // 获取微信胶囊的位置信息 width,height,top,right,left,bottom
      const custom = wx.getMenuButtonBoundingClientRect();
      // console.log(custom)

      // 导航栏高度(标题栏高度) = 胶囊高度 + (顶部距离 - 状态栏高度) * 2
      state.globalData.navigationBarHeight =
        custom.height + (custom.top - state.globalData.statusBarHeight) * 2;
      // console.log("导航栏高度："+state.globalData.navigationBarHeight)

      // 总体高度 = 状态栏高度 + 导航栏高度
      state.globalData.navHeight =
        state.globalData.navigationBarHeight + state.globalData.statusBarHeight;

      // #endif

      state.globalData.windowHeight = systemInfo.windowHeight;
      state.globalData.windowWidth = systemInfo.windowWidth;

      console.log(state.globalData);
    },
    subscribeTopic(state) {
      state.mqtt.subscribe(
        state.subscribeArr,
        {
          qos: 0,
        },
        (error) => {
          if (!error) {
            console.log(`Subscribed to ${state.subscribeArr}`);
          } else {
            console.error("Subscribe error:", error);
          }
        }
      );
    },
    publishMessage(state, { topic, msg }) {
      console.log(topic, msg, state.mqtt);
      state.mqtt.publish(topic, msg, {
        qos: 2,
        retain: false,
      });
    },
    disconnectMqtt(state) {
      if (state.mqtt && state.mqtt.connected) {
        state.mqtt.end();
      }
    },
    // 保存个人信息
    saveUserInfo(state, userInfo) {
      state.userInfo = userInfo;
    },
    // 修改添加好友信息
    setMessageValue(state, payLoad) {
      state.messageValue = payLoad;
    },
  },
  actions: {
    async openMqtt({ state, commit, dispatch }) {
      let status = await dispatch("getMqttStatus");
      if (status) return;
      return new Promise((resolve, reject) => {
        const { server, clientId } = state.appData.config.mqtt;
        connectMqtt(server, clientId, {
          success: (client) => {
            console.log("mqtt启动");
            commit("$uStore", {
              name: "mqtt",
              value: client,
            });
            resolve();
          },
          fail: () => {
            console.log("mqtt启动失败");
            commit("$uStore", {
              name: "mqtt",
              value: null,
            });
            resolve();
          },
        });
      });
    },
    getMqttStatus({ state }) {
      if (state.mqtt == null) return false;
      return state.mqtt.connected;
    },
  },
});

if (Object.keys(lifeData).length > 0) {
  store.replaceState(Object.assign(store.state, lifeData));
}

export default store;
